package com.easylinkin.linkappapi.common.utils;

import org.junit.Test;
import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p></p>
 *
 * @author TongJie
 * @since 2021/5/24 14:32
 */
public class ExpressionUtil {

    /**
     * 日志记录
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExpressionUtil.class);


    /**
     * @param dataType 数据类型
     * @param before 前值
     * @param calculateSign 表达式
     * @param after 后值
     * @return 判断结果
     */
    public static boolean checkExpressionMeet(String dataType, String before, String calculateSign, String after) {
        boolean isString = "string".equals(dataType);
        StringBuilder expression = new StringBuilder();
//            如果类型是字符串会报错 所以加单引号
        if (isString) {
            expression.append("'");
        }
        expression.append(before.trim());
        if (isString) {
            expression.append("'");
        }
        expression.append(calculateSign);
        if (isString) {
            expression.append("'");
        }
        expression.append(after.trim());
        if (isString) {
            expression.append("'");
        }
        expression.append(" ");
        LOGGER.info("表达式为：{}", expression);

        return MVEL.eval(wrapperExpression(expression.toString()), Boolean.TYPE);
    }

    @Test
    public void test() {
        String[] strings = {"00.000>=2", "0==1", "1==1", "0 ==0", "00.006>=2", "000.006>=2", "0.03>1", "00.12== 2",
                "00.003>=2", "0.117>=2", " 0.117 <=2 ", "0==1", "'abcd'=='abcd'", " 0.117 ==2 "};
        for (String string : strings) {
            boolean r = MVEL.eval(wrapperExpression(string), Boolean.TYPE);
            System.out.println(r);
        }
    }

    /**
     * 容错包装表达式，避免出错，避免 00.006>=2类，判断报错
     *
     * @param string
     * @return
     */
    private static String wrapperExpression(final String string) {
        String regex = "(>=|<=|>|<|==)";
        String[] ss = string.split(regex);
        try {
            String result = string.replaceFirst("^" + ss[0], Double.valueOf(ss[0]).toString());
            LOGGER.info(string + " 容错转换后表达式为：{}", result);
            return result;
        } catch (Exception e) {
            LOGGER.info(string + " 表达式放弃转换：" + e.getMessage());
            return string;
        }
    }


}
